#include <QtSql>

#include "pipelineform.h"
#include "ui_pipelineform.h"
#include "dbconnection.h"
#include "tabbuilder.h"


PipeLineForm::PipeLineForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PipeLineForm)
{
    ui->setupUi(this);
    if(dbconnection::instance()->connected())
    {
        statusModel = new QSqlQueryModel();
        statusModel->setQuery("select getEnumValues('EnumgnOperationalStatus')", dbconnection::instance()->database());
        ui->comboBoxOperationalStatus->setModel(statusModel);
        ui->comboBoxOperationalStatus->setModelColumn(0);
        categoryModel = new QSqlQueryModel();
        categoryModel->setQuery("select getEnumValues('EnumclLineLoopCategory')", dbconnection::instance()->database());
        ui->comboBoxCategory->setModel(categoryModel);
        ui->comboBoxCategory->setModelColumn(0);
        historyModel = new QSqlQueryModel();
        historyModel->setQuery("select getEnumValues('EnumgnHistoricalState')", dbconnection::instance()->database());
        ui->comboBoxHistoricalState->setModel(historyModel);
        ui->comboBoxHistoricalState->setModelColumn(0);
        ui->wcLineType->setTable("cllineservicetype");
        ui->wcParentLine->setTable("lineloop");
        ui->wcProduct->setTable("product");
    }
    changeEditMode();
    connect(ui->pushButtonStartStopEdit, SIGNAL(clicked()), this, SLOT(changeEditMode()));
    connect(ui->pushButtonSaveEdit, SIGNAL(clicked()), this, SLOT(submit()));

    model = new TreeModel("lineloop", "linename", this);
    ui->treeView->setModel(model);
    ui->treeView->setColumnWidth(0, ui->treeView->width()*.8);
    ui->treeView->hideColumn(1);
    connect(ui->treeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectLineLoop(QModelIndex)));
}

PipeLineForm::~PipeLineForm()
{
    delete ui;
    delete lineLoop;
    delete mLineLoopPassport;
}

void PipeLineForm::loadData(const QString theFeatureID)
{
    featureID = theFeatureID;
    lineLoop = new LineLoop(QUuid(theFeatureID));    
    QString whereClause = "lineloopeventid='"+theFeatureID+"' and historicalstate::text='Текущий'";
    //QMessageBox::information(this, "info", whereClause);
    mLineLoopPassport = new LineLoopPassport(whereClause);
    //QMessageBox::information(0, "info", "created lineloop object");
    revert();
    TabBuilder::fillTabControl(ui->tabWidget, "pipelineform" , theFeatureID);
}

void PipeLineForm::changeEditMode()
{
    bool enableEdit = ui->pushButtonStartStopEdit->isChecked();
    ui->pushButtonSaveEdit->setEnabled(enableEdit);

    //tab "Основные сведения"
    ui->lineEditName->setReadOnly(!enableEdit);
    ui->comboBoxOperationalStatus->setEnabled(enableEdit);
    ui->textEditRemark->setReadOnly(!enableEdit);
    ui->wcLineType->setReadOnly(!enableEdit);
    ui->wcParentLine->setReadOnly(!enableEdit);

    //tab "Текущие паспортные данные"
    ui->lineEditRegNum->setReadOnly(!enableEdit);
    ui->lineEditUsage->setReadOnly(!enableEdit);
    ui->comboBoxCategory->setEnabled(enableEdit);
    ui->lineEditLengthByPassport->setReadOnly(!enableEdit);
    ui->lineEditLengthBySurvey->setReadOnly(!enableEdit);
    ui->lineEditPressureByPassport->setReadOnly(!enableEdit);
    ui->lineEditTemperatureByPassport->setReadOnly(!enableEdit);
    ui->wcProduct->setReadOnly(!enableEdit);

    //tab "Архивные данные и аудит"
    ui->comboBoxHistoricalState->setEnabled(enableEdit);
    ui->fdcServiceFrom->setEnabled(enableEdit);
    ui->fdcServiceTo->setEnabled(enableEdit);
    //ui->lineEditInServiceDateFrom->setReadOnly(!enableEdit);
    //ui->lineEditInServiceDateTo->setReadOnly(!enableEdit);
}

void PipeLineForm::submit()
{
    lineLoop->setLineName(ui->lineEditName->text());
    lineLoop->setOperationalStatus(ui->comboBoxOperationalStatus->currentText());
    lineLoop->setRemarks(ui->textEditRemark->toPlainText());
    lineLoop->setLineType(ui->wcLineType->currentID());
    lineLoop->setGroupEventID(ui->wcParentLine->currentID());
    lineLoop->setEffectiveFromDate(ui->fdcServiceFrom->date());
    lineLoop->setEffectiveToDate(ui->fdcServiceTo->date());
    lineLoop->saveObject();
    mLineLoopPassport->setRegisterNumber(ui->lineEditRegNum->text());
    mLineLoopPassport->setPurpose(ui->lineEditUsage->text());
    mLineLoopPassport->setCategory(ui->comboBoxCategory->currentText());
    mLineLoopPassport->setLength(ui->lineEditLengthByPassport->text().toDouble());
    mLineLoopPassport->setLengthBySurvey(ui->lineEditLengthBySurvey->text().toDouble());
    mLineLoopPassport->setPressureByPassport(ui->lineEditPressureByPassport->text().toDouble());
    mLineLoopPassport->setTemperatureByPassport(ui->lineEditTemperatureByPassport->text().toDouble());
    mLineLoopPassport->saveObject();
}

void PipeLineForm::revert()
{
    //вернуть изначальные
    //tab "Основные сведения"
    ui->lineEditName->setText(lineLoop->lineName());
    ui->comboBoxOperationalStatus->setCurrentIndex(
            ui->comboBoxOperationalStatus->findText(lineLoop->operationalStatus()));
    ui->textEditRemark->setText(lineLoop->remarks());

    ui->wcLineType->setID(lineLoop->lineType().toString());
    ui->wcParentLine->setID(lineLoop->groupEventID().toString());


    //tab "Текущие паспортные данные"

    ui->lineEditRegNum->setText(mLineLoopPassport->registerNumber());
    ui->lineEditUsage->setText(mLineLoopPassport->purpose());
    ui->comboBoxCategory->setCurrentIndex(
            ui->comboBoxCategory->findText(mLineLoopPassport->category()));

    ui->wcProduct->setID(mLineLoopPassport->productByPassport());

    ui->lineEditLengthByPassport->setText(QString("%1").arg(mLineLoopPassport->length()));
    ui->lineEditLengthBySurvey->setText(QString("%1").arg(mLineLoopPassport->lengthBySurvey()));
    ui->lineEditPressureByPassport->setText(QString("%1").arg(mLineLoopPassport->pressureByPassport()));
    ui->lineEditTemperatureByPassport->setText(QString("%1").arg(mLineLoopPassport->temperatureByPassport()));


    mountingModel = new QSqlQueryModel(this);
    QSqlQuery qm(dbconnection::instance()->database());
    qm.prepare("select * from linelooppassportcompany where linelooppassporteventid=?");
    qm.bindValue(0, mLineLoopPassport->eventID().toString());
    mountingModel->setQuery(qm);
    ui->tableViewMounting->setModel(mountingModel);

    //tab "Архивные данные и аудит"
    ui->lineEditEventID->setText(featureID);
    ui->fdcServiceFrom->setDate(lineLoop->effectiveFromDate());
    ui->fdcServiceTo->setDate(lineLoop->effectiveToDate());
    ui->comboBoxHistoricalState->setCurrentIndex(
            ui->comboBoxHistoricalState->findText(lineLoop->historicalState()));
    ui->lineEditCreatedBy->setText(lineLoop->createdBy());
    ui->lineEditCreatedDate->setText(lineLoop->createdDate().toString());
    ui->lineEditModifiedBy->setText(lineLoop->modifiedBy());
    ui->lineEditModifiedDate->setText(lineLoop->lastModified().toString());
}

void PipeLineForm::selectLineLoop(QModelIndex idx)
{
    TreeNode *node = static_cast<TreeNode*>(idx.internalPointer());
    loadData(node->data(1).toString());
    //QMessageBox::information(0, "selected eventid", node->data(1).toString());
}

